package com.tange.ai.iot.client.gnssa.service

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityServiceListBinding
import com.tange.ai.iot.client.gnssa.message.MessageSettingActivity
import com.tange.base.toolkit.*
import com.tange.core.cloud.message.*
import com.tange.core.value.added.service.Service
import com.tange.core.value.added.service.ValueAddedService

/**
 * 设备当前的增值服务信息
 */
class ValueAddedServiceActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "ValueAddedServiceActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, ValueAddedServiceActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var binding: ActivityServiceListBinding
    private lateinit var listAdapter: ListAdapter
    private lateinit var deviceId: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        binding = ActivityServiceListBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
        }


        binding.plan.onClicked { ValueAddedPlanActivity.launch(it.context, deviceId) }
        binding.order.onClicked { ValueAddedOrderActivity.launch(it.context, deviceId) }

        binding.top.left.onClicked { finish() }
        binding.top.right.onClicked { MessageSettingActivity.launch(it.context, deviceId) }

        listAdapter = ListAdapter()
        binding.serviceList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.serviceList.adapter = listAdapter

        queryDeviceService()
    }

    private fun queryDeviceService() {

        binding.loading.visible()
        binding.emptyView.gone()


        ValueAddedService.queryServiceOfDevice(deviceId) {
            binding.loading.gone()
            if (it.success) {
                it.data?.let {
                    if ((it.services?.size?:0) <= 0) {
                        binding.emptyView.visible()
                        binding.serviceList.gone()
                    } else {
                        it.services?.let {
                            listAdapter.refresh(it)
                        }
                        binding.emptyView.gone()
                        binding.serviceList.visible()
                    }
                }
            } else {
                Tips.show("请求失败：${it.code}, ${it.message}")
            }
        }
    }

    inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private val services: MutableList<Service> = java.util.ArrayList()

        fun refresh(list: List<Service>) {
            services.clear()
            services.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.item_service_list, viewGroup, false)
            return ViewHolderMessage(view)
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

            if (holder is ViewHolderMessage) {
                val viewHolderMessage: ViewHolderMessage = holder
                val item = services[position]

                val startTime = ((item.start ?: 0) * 1000L)
                val endTime = ((item.end ?: 0) * 1000L)
                val now = System.currentTimeMillis()
                val isValid = if (now in startTime..endTime) "【生效中】" else "【已过期】"

                var serviceType = isValid
                item.abilities?.let { ability ->
                    ability.storage?.let {
                        if ((it.keepDays ?: 0) > 0) {

                            if (it.recordingMode == "INCIDENT") {
                                serviceType += "云存储（事件录像）"
                            } else {
                                serviceType += "云存储（全天录像）"
                            }
                        }
                    }

                    ability.traffic?.let {
                        if (!TextUtils.isEmpty(it.limitMode)) {
                            if (!TextUtils.isEmpty(serviceType)) { serviceType += "\n" }
                            serviceType += "数据流量（${it.limitMode}, ${it.trafficLimit}）"
                        }
                    }

                    ability.ai?.let {
                        if ((it.algorithm?.size ?: 0) > 0) {
                            if (!TextUtils.isEmpty(serviceType)) { serviceType += "\n" }
                            serviceType += "智能识别（${it.algorithm?.get(0)}等）"
                        }
                    }

                    ability.smartBox?.let {
                        if ((it.supported?.size ?: 0) > 0) {
                            if (!TextUtils.isEmpty(serviceType)) { serviceType += "\n" }
                            serviceType += "智能音箱（${it.supported?.get(0)}等）"
                        }
                    }
                }

                viewHolderMessage.name.text = serviceType
                val start = ((item.start ?: 0) * 1000L).asTime()
                val end = ((item.end ?: 0) * 1000L).asTime()
                viewHolderMessage.start.text = "开始时间：$start"
                viewHolderMessage.end.text = "结束时间：$end"
            }
        }

        override fun getItemCount(): Int = services.size
    }

    class ViewHolderMessage(view: View) : RecyclerView.ViewHolder(view) {
        val name: TextView
        val start: TextView
        val end: TextView

        init {
            name = view.findViewById(R.id.name)
            start = view.findViewById(R.id.start)
            end = view.findViewById(R.id.end)

        }
    }
}